package com.fh.shop.api.interceptors;

import com.fh.shop.api.annotation.Idempotency;
import com.fh.shop.api.common.ResponseEnum;
import com.fh.shop.api.exception.IdempotencyException;
import com.fh.shop.util.RedisUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;

public class TokenInterceptor extends HandlerInterceptorAdapter {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //获得请求头信息
        if (!(handler instanceof HandlerMethod)){
            return true;
        }
        HandlerMethod handlerMethod = (HandlerMethod) handler;
        //获得方法
        Method method = handlerMethod.getMethod();
        //判断方法有没有注解
        if (!method.isAnnotationPresent(Idempotency.class)){
            //没注解说明不需要判断幂等性
            return true;
        }

        //验证请求头
        String header = request.getHeader("x-idempotency");
        if (StringUtils.isEmpty(header)){
            throw new IdempotencyException(ResponseEnum.TOKEN_HEADER_IS_NULL);
        }

        //有注解说明需要判断幂等性 避免重复添加商品
//        String key = KeyUtil.tokenKey(header);
        long del = RedisUtil.del(header);
        if (del == 0){
            //等于1 说明第一次购买 等于0说明已经下过订单了
            throw new IdempotencyException(ResponseEnum.TOKEN_REPEAT);
        }

        return true;
    }
}
